<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="105px">
      <el-form-item label="活动标题" prop="activityTitle">
        <el-input
          v-model="queryParams.activityTitle"
          placeholder="请输入活动标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="活动类型" prop="activityType">
        <el-select v-model="queryParams.activityType" placeholder="请选择活动类型" clearable>
          <el-option
            v-for="item in activityTypeOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="社团" prop="clubId">
        <el-select v-model="queryParams.clubId" placeholder="请选择社团" clearable>
          <el-option
            v-for="item in clubList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="活动开始时间">
        <el-date-picker
          v-model="daterangeStartTime"
          style="width: 240px"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="活动结束时间">
        <el-date-picker
          v-model="daterangeEndTime"
          style="width: 240px"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="报名开始时间">
        <el-date-picker
          v-model="daterangeSignUpStartTime"
          style="width: 240px"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="报名结束时间">
        <el-date-picker
          v-model="daterangeSignUpEndTime"
          style="width: 240px"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['campus:activity:add']"
        >发布</el-button>
      </el-col>
      <!-- <el-col :span="1.5"> -->
        <!-- <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['campus:activity:edit']"
        >修改</el-button> -->
      <!-- </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-upload"
          size="mini"
          :disabled="multiple"
          @click="handlePublish"
          v-hasPermi="['campus:activity:edit']"
        >发布</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['campus:activity:remove']"
        >删除</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleCancel"
          v-hasPermi="['campus:activity:remove']"
        >取消</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['campus:activity:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-view"
          size="mini"
          @click="handleViewMyRegistrations"
        >查看我的报名活动</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="activityList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="活动标题" align="center" prop="activityTitle" />
      <el-table-column label="社团名称" align="center">
        <template slot-scope="scope">
          {{ getClubName(scope.row.clubId) }}
        </template>
      </el-table-column>
      <el-table-column label="活动结束时间" align="center" prop="endTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="报名结束时间" align="center" prop="signUpEndTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.signUpEndTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="活动状态" align="center">
        <template slot-scope="scope">
          <el-tag :type="getActivityStatusType(scope.row.activityStatus)">
            {{ getActivityStatusText(scope.row.activityStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="报名人数上限" align="center" prop="signUpLimit" />
      <el-table-column label="当前报名人数" align="center" prop="currentSignUpNum" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['campus:activity:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            @click="handlePublish(scope.row)"
            v-hasPermi="['campus:activity:edit']"
            v-if="scope.row.activityStatus === 0"
          >发布</el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleSignUp(scope.row)"
            v-hasPermi="['campus:activity:edit']"
            v-if="scope.row.activityStatus === 1"
          >报名</el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleCancel(scope.row)"
            v-hasPermi="['campus:activity:remove']"
            v-if="scope.row.activityStatus !== 3 && scope.row.activityStatus !== 4"
          >取消</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改校内活动对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="111px">
        <el-form-item label="活动标题" prop="activityTitle">
          <el-input v-model="form.activityTitle" placeholder="请输入活动标题" />
        </el-form-item>
        <el-form-item label="活动内容" prop="activityContent">
          <el-input v-model="form.activityContent" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="活动类型" prop="activityType">
          <el-select v-model="form.activityType" placeholder="请选择活动类型">
            <el-option
              v-for="item in activityTypeOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="活动上限人数" prop="signUpLimit">
          <el-input-number v-model="form.signUpLimit" controls-position="right" :min="-1" />
          <div style="font-size: 12px; color: #999; margin-top: 5px;">-1表示无限制</div>
        </el-form-item>
        <el-form-item label="社团" prop="clubId">
          <el-select v-model="form.clubId" placeholder="请选择社团">
            <el-option v-for="item in clubList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="活动地点" prop="activityLocation">
          <el-input v-model="form.activityLocation" placeholder="请输入活动地点" />
        </el-form-item>
        <el-form-item label="活动开始时间" prop="startTime">
          <el-date-picker clearable
            v-model="form.startTime"
            type="date"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择活动开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="活动结束时间" prop="endTime">
          <el-date-picker clearable
            v-model="form.endTime"
            type="date"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择活动结束时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="报名开始时间" prop="signUpStartTime">
          <el-date-picker clearable
            v-model="form.signUpStartTime"
            type="date"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择报名开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="报名结束时间" prop="signUpEndTime">
          <el-date-picker clearable
            v-model="form.signUpEndTime"
            type="date"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择报名结束时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    
    <!-- 我的报名活动对话框 -->
    <el-dialog title="我的报名活动" :visible.sync="openMyRegistrations" width="900px" append-to-body>
      <el-table 
        v-loading="loading" 
        :data="myRegistrations"
        border
        style="width: 100%"
        :header-cell-style="{background:'#f5f7fa', color:'#606266'}"
      >
        <el-table-column label="活动标题" align="center" prop="activityTitle">
          <template slot-scope="scope">
            <el-tag type="primary">{{ scope.row.activityTitle }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="活动地点" align="center" prop="activityLocation" />
        <el-table-column label="活动开始时间" align="center" prop="startTime" width="180">
          <template slot-scope="scope">
            <i class="el-icon-time"></i>
            <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="报名时间" align="center" prop="registrationTime" width="180">
          <template slot-scope="scope">
            <i class="el-icon-time"></i>
            <span>{{ parseTime(scope.row.registrationTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" width="120">
          <template slot-scope="scope">
            <el-tag :type="getActivityStatusType(scope.row.activityStatus)">
              {{ getActivityStatusText(scope.row.activityStatus) }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="openMyRegistrations = false" icon="el-icon-close">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listActivity, getActivity, delActivity, addActivity, updateActivity, cancelActivity, publishActivity } from "@/api/campus/activity"
import { listActivityType } from "@/api/campus/activityType"
import { listClub } from "@/api/campus/club"
import { addRegistration, listMyRegistrations } from "@/api/campus/registration"

export default {
  name: "Activity",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 校内活动表格数据
      activityList: [],
      // 活动类型选项
      activityTypeOptions: [],
      // 社团选项
      clubList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示我的报名活动弹出层
      openMyRegistrations: false,
      // 我的报名活动数据
      myRegistrations: [],
      // 报名结束时间时间范围
      daterangeStartTime: [],
      // 报名结束时间时间范围
      daterangeEndTime: [],
      // 报名结束时间时间范围
      daterangeSignUpStartTime: [],
      // 报名结束时间时间范围
      daterangeSignUpEndTime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        activityTitle: null,
        activityType: null,
        clubId: null,
        startTime: null,
        endTime: null,
        signUpStartTime: null,
        signUpEndTime: null,
        activityStatus: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        activityTitle: [
          { required: true, message: "活动标题不能为空", trigger: "blur" }
        ],
        activityContent: [
          { required: true, message: "活动内容不能为空", trigger: "blur" }
        ],
        activityType: [
          { required: true, message: "活动类型不能为空", trigger: "change" }
        ],
        clubId: [
          { required: true, message: "关联社团表的主键ID不能为空", trigger: "blur" }
        ],
        activityLocation: [
          { required: true, message: "活动地点不能为空", trigger: "blur" }
        ],
        startTime: [
          { required: true, message: "活动开始时间不能为空", trigger: "blur" }
        ],
        endTime: [
          { required: true, message: "活动结束时间不能为空", trigger: "blur" }
        ],
        signUpStartTime: [
          { required: true, message: "报名开始时间不能为空", trigger: "blur" }
        ],
        signUpEndTime: [
          { required: true, message: "报名结束时间不能为空", trigger: "blur" }
        ],
      }
    }
  },
  created() {
    this.getActivityTypeList()
    this.getClubList()
    this.getList()
  },
  methods: {
    /** 根据社团ID获取社团名称 */
    getClubName(clubId) {
      if (!clubId) return "";
      const club = this.clubList.find(item => item.id === clubId);
      return club ? club.name : "";
    },
    /** 获取活动状态文本 */
    getActivityStatusText(status) {
      const statusMap = {
        0: '草稿',
        1: '已发布',
        2: '进行中',
        3: '已结束',
        4: '已取消'
      };
      return statusMap[status] || '未知状态';
    },
    /** 获取活动状态标签类型 */
    getActivityStatusType(status) {
      const typeMap = {
        0: 'info',    // 草稿 - 灰色
        1: 'primary', // 已发布 - 蓝色
        2: 'success', // 进行中 - 绿色
        3: 'warning', // 已结束 - 橙色
        4: 'danger'   // 已取消 - 红色
      };
      return typeMap[status] || 'info';
    },
    /** 查询活动类型列表 */
    getActivityTypeList() {
      listActivityType().then(response => {
        this.activityTypeOptions = response.rows
      })
    },
    /** 查询社团列表 */
    getClubList() {
      listClub({ pageSize: 10000 }).then(response => {
        this.clubList = response.rows
      })
    },
    /** 查询校内活动列表 */
    getList() {
      this.loading = true
      this.queryParams.params = {}
      if (null != this.daterangeStartTime && '' != this.daterangeStartTime) {
        this.queryParams.params["beginStartTime"] = this.daterangeStartTime[0]
        this.queryParams.params["endStartTime"] = this.daterangeStartTime[1]
      }
      if (null != this.daterangeEndTime && '' != this.daterangeEndTime) {
        this.queryParams.params["beginEndTime"] = this.daterangeEndTime[0]
        this.queryParams.params["endEndTime"] = this.daterangeEndTime[1]
      }
      if (null != this.daterangeSignUpStartTime && '' != this.daterangeSignUpStartTime) {
        this.queryParams.params["beginSignUpStartTime"] = this.daterangeSignUpStartTime[0]
        this.queryParams.params["endSignUpStartTime"] = this.daterangeSignUpStartTime[1]
      }
      if (null != this.daterangeSignUpEndTime && '' != this.daterangeSignUpEndTime) {
        this.queryParams.params["beginSignUpEndTime"] = this.daterangeSignUpEndTime[0]
        this.queryParams.params["endSignUpEndTime"] = this.daterangeSignUpEndTime[1]
      }
      listActivity(this.queryParams).then(response => {
        this.activityList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        activityTitle: null,
        activityContent: null,
        activityType: null,
        clubId: null,
        activityLocation: null,
        startTime: null,
        endTime: null,
        signUpStartTime: null,
        signUpEndTime: null,
        activityStatus: null,
        signUpLimit: null,
        currentSignUpNum: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeStartTime = []
      this.daterangeEndTime = []
      this.daterangeSignUpStartTime = []
      this.daterangeSignUpEndTime = []
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加校内活动"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getActivity(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改校内活动"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateActivity(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addActivity(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除校内活动编号为"' + ids + '"的数据项？').then(function() {
        return delActivity(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('campus/activity/export', {
        ...this.queryParams
      }, `activity_${new Date().getTime()}.xlsx`)
    },
    /** 取消按钮操作 */
    handleCancel(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认取消校内活动编号为"' + ids + '"的数据项？').then(function() {
        return cancelActivity(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("取消成功")
      }).catch(() => {})
    },
    /** 发布按钮操作 */
    handlePublish(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认发布校内活动编号为"' + ids + '"的数据项？').then(function() {
        return publishActivity(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("发布成功")
      }).catch(() => {})
    },
    /** 报名按钮操作 */
    handleSignUp(row) {
      this.$modal.confirm('是否确认报名参加"' + row.activityTitle + '"活动？').then(() => {
        return addRegistration({ activityId: row.id })
      }).then(() => {
        this.$modal.msgSuccess("报名成功")
        this.getList()
      }).catch(() => {})
    },
    /** 查看我的报名活动 */
    handleViewMyRegistrations() {
      const userId = this.$store.getters.id;
      console.log('当前用户ID:', userId);
      if (!userId) {
        this.$modal.msgError("无法获取当前用户信息");
        return;
      }
      this.loading = true;
      console.log('正在调用 listMyRegistrations 接口，用户ID:', userId);
      // 先尝试使用测试用户ID 1
      const testUserId = userId || 1;
      listMyRegistrations(testUserId).then(response => {
        console.log('我的报名活动数据:', response);
        // 根据后端实际返回的数据结构调整
        this.myRegistrations = response.rows || response.data || response || [];
        console.log('处理后的数据:', this.myRegistrations);
        this.openMyRegistrations = true;
        this.loading = false;
        
        // 添加测试数据以验证对话框显示
        if (this.myRegistrations.length === 0) {
          console.log('没有报名活动数据');
          // 显示一个提示信息
          this.$modal.msgWarning("您还没有报名任何活动");
        }
      }).catch(error => {
        console.error('获取我的报名活动失败:', error);
        this.$modal.msgError("获取我的报名活动失败: " + (error.message || error));
        this.loading = false;
      })
    }
  }
}
</script>
